package com.jsptpd.smartauth.modules.business.restcontrol;

import com.jsptpd.smartauth.common.util.AppAuthUtils;
import com.jsptpd.smartauth.common.util.HttpUtils;
import com.jsptpd.smartauth.modules.business.model.Error;
import com.jsptpd.smartauth.modules.business.model.RespObj;
import com.jsptpd.smartauth.modules.business.utils.Constants;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private HttpServletResponse httpServletResponse;
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Value("${config.message.bulletin.publish}")
    Boolean bulletinPublish;
    @Value("${config.message.bulletin.title}")
    String bulletinTitle;
    @Value("${config.message.bulletin.content}")
    String bulletinContent;

    @ApiOperation(value="获取系统公告", notes="先简单弹出提示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "String", paramType = "path"),
    })
    @ResponseBody
    @RequestMapping(value = "/bulletin", method = RequestMethod.GET)
    public RespObj<Object> getBulletin() {
        Error error;
        RespObj<String> respData;

        //校验appId
        if(!AppAuthUtils.checkAppIdAndKey(httpServletRequest)){
            error = new Error(Constants.COMMON_ERRCODE_FAIL,Constants.COMMON_ERRMSG_FAIL);
            return new RespObj<>(error,"");
        }
        //校验token
        String token = HttpUtils.getTokenInHeaders(httpServletRequest);
        if(token==null && token.isEmpty()){
            error = new Error(Constants.COMMON_ERRCODE_FAIL,Constants.COMMON_ERRMSG_FAIL);
            return new RespObj<>(error,"");
        }

        if(bulletinPublish){
            JSONObject bulletin = new JSONObject();
            try {
                bulletin.put("title",bulletinTitle);
                bulletin.put("content",bulletinContent);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            error = new Error(Constants.COMMON_ERRCODE_SUCC,Constants.COMMON_ERRMSG_SUCC);
            return new RespObj<>(error,bulletin.toString());
        }else{
            error = new Error(Constants.COMMON_ERRCODE_FAIL,Constants.COMMON_ERRMSG_FAIL);
            return new RespObj<>(error,"");
        }
    }

}
